package com.demo.rabbit.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class MessageListener {

    public static final String DLX_EXCHANGE_NAME = "dlx.exchange.pay";

    public static final String DLX_QUEUE_NAME = "dlx.queue.pay";

    public static final String DLX_ROUTING_KEY_NAME = "dlx.routing.pay";


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = DLX_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(value = DLX_EXCHANGE_NAME, durable = "true"),
            key = {DLX_ROUTING_KEY_NAME}
        )
    )
    public void processMessage(String data, Message message, Channel channel) {
        try {
            log.info("消息消费端，接收到的消息内容：{}", data);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            try {
                Boolean redelivered = message.getMessageProperties().getRedelivered();
                if(redelivered) {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                }else{
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
